package org.haier.aws.lambda;

import com.amazonaws.services.iot.AWSIot;
import com.amazonaws.services.iot.model.AttachPolicyRequest;
import com.amazonaws.services.iot.model.AttachThingPrincipalRequest;
import com.amazonaws.services.iot.model.CreateThingRequest;
import com.amazonaws.services.iot.model.UpdateCertificateRequest;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import org.haier.aws.config.JITRConfig;
import org.haier.aws.dto.JITRDto;
import org.haier.aws.utils.AWSIotUtils;

/**
 * JITR方式注册
 *
 * @author: SongKun
 * @date: 2021/5/12
 */
public class JITR implements RequestHandler<JITRDto, Object> {

    @Override
    public Object handleRequest(JITRDto dto, Context context) {
        LambdaLogger logger = context.getLogger();
        logger.log("收到输入信息：" + dto);
        String accountId = dto.getAwsAccountId();
        String certificateId = dto.getCertificateId();
        // 获取AWWIot
        AWSIot awsIot = AWSIotUtils.getAwsIot();
        // 组装证书ARN
        String certificateARN = AWSIotUtils.getCertificateARN(accountId, certificateId);
        // 将策略附件到设备证书上
        awsIot.attachPolicy(new AttachPolicyRequest()
                .withPolicyName(JITRConfig.POLICY_NAME)
                .withTarget(certificateARN));
        // 激活证书
        awsIot.updateCertificate(new UpdateCertificateRequest()
                .withCertificateId(certificateId)
                .withNewStatus("ACTIVE"));
        // 创建Thing
        awsIot.createThing(new CreateThingRequest().withThingName(dto.getCertificateId()));
        // 将证书挂在Thing下面
        awsIot.attachThingPrincipal(new AttachThingPrincipalRequest()
                .withThingName(dto.getCertificateId())
                .withPrincipal(certificateARN));
        return "200";
    }
}
